package com.luyuan.crm.sale.web;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.faces.model.DataModel;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.luyuan.crm.member.model.Member;
import com.luyuan.crm.member.service.MemberService;
import com.luyuan.crm.sale.model.Order;
import com.luyuan.crm.sale.service.OrderService;
import com.ruijie.web.jsf.action.BaseAction;
import com.ruijie.web.jsf.context.TableContext;
import com.ruijie.web.jsf.model.PageDataModel;
import com.ruijie.web.jsf.model.TableOrder;
import com.ruijie.web.jsf.model.TablePage;
import com.ruijie.foundation.query.Page;
import com.ruijie.foundation.query.criteria.CriteriaTemplate;
import com.ruijie.foundation.query.criteria.RestrictionTemplate;

@Component("orderMemberAciton")
@Scope("view")
public class OrderMemberAciton extends BaseAction implements InitializingBean {
    @Resource(name = "orderService")
    private OrderService orderService;

    private String memberId;

    @Resource(name = "memberService")
    private MemberService memberService;

    public DataModel getOrderTableModel() {
        TablePage tablePage = TableContext.getTablePage();
        List<TableOrder> tableOrders = TableContext.getTableOrders();
        List<org.hibernate.criterion.Order> orders = new ArrayList<org.hibernate.criterion.Order>();
        for (TableOrder tableOrder : tableOrders) {
            org.hibernate.criterion.Order order = tableOrder.toOrder();
            if (order != null) {
                orders.add(order);
            }
        }
        Member member = memberService.getById(memberId);
        CriteriaTemplate c = CriteriaTemplate.forClass(Order.class);
        RestrictionTemplate r = new RestrictionTemplate(false);
        // c.add(r.eq("saleman", AppUserContext.getCurrentUser()));
        c.add(r.eq("member", member));

        Page page = orderService.pagedQuery(c, tablePage.getPage(), tablePage.getPageSize(), orders);
        return new PageDataModel(page);
    }

    public void toOrderPage(String memberRequesetId) {
        setRequestAttribute("member", memberRequesetId, true);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        memberId = (String) getRequestAttribute("memberId");
    }
}
